package org.spiderflow.common.io;

import java.util.regex.Pattern;

/**
 * 文本查找处理器
 *
 * @author zhaoshihao
 * @version 2021/10/27 16:54
 */
public class TextFindHandler {
    private final String keywords;
    private final boolean matchCase;
    private final Pattern pattern;

    public TextFindHandler(String keywords, boolean matchCase, Pattern pattern) {
        this.keywords = keywords;
        this.matchCase = matchCase;
        this.pattern = pattern;
    }

    public String getKeywords() {
        return keywords;
    }

    public boolean isMatchCase() {
        return matchCase;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public boolean find(String text) {
        return pattern == null ? findByKeywords(text) : findByRegex(text);
    }

    private boolean findByKeywords(String text) {
        return this.matchCase ? text.contains(keywords) : text.toLowerCase().contains(keywords.toLowerCase());
    }

    private boolean findByRegex(String text) {
        return pattern.matcher(text).find();
    }
}
